package com.zzld.modules.sys.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzld.modules.common.SessionUser;
import com.zzld.modules.common.dto.EasyuiTree;
import com.zzld.modules.sys.entity.Res;
import com.zzld.modules.sys.service.IRoleResService;

/**
 * 角色资源
 * 
 * @author zzld
 */
@Controller
@RequestMapping(value = "/sys/roleRes")
public class RoleResController {

	@Autowired
	private IRoleResService roleResService;

	@RequestMapping(value = "/getUserRes")
	@ResponseBody
	// 获取当前用户角色的权限集合
	private Map<Integer, List<Res>> getUserRes(String uid) {
		Map<Integer, List<Res>> resMap = new HashMap<Integer, List<Res>>();
		List<Res> resList = null;
		try {
			resList = roleResService.getUserRes(uid);
			if (resList.size() > 0) {
				for (Res res : resList) {
					if (!resMap.containsKey(res.getIslast())) {
						resMap.put(res.getIslast(), new ArrayList<Res>());
					}
					resMap.get(res.getIslast()).add(res);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return resMap;
	}

	/**
	 * 根据ID获取当前用户资源
	 * 
	 * @param rid
	 * @return
	 */
	@RequestMapping("/getUserResTreeById")
	@ResponseBody
	private List<EasyuiTree> getUserResTreeById(
			@RequestParam(value = "pid") String pid) {
		List<EasyuiTree> nodes = new ArrayList<EasyuiTree>();
		String uid = SessionUser.getShiroUser().getId();
		try {
			List<Res> resList = roleResService.getResTreeById(uid, pid);
			if (resList == null) {
				return null;
			}
			for (Res res : resList) {
				EasyuiTree node = new EasyuiTree();
				node.setId(res.getId());
				node.setText(res.getName());
				if (!StringUtils.isBlank(res.getPid())) {
					node.setPid(res.getPid());
				}
				Map<String, String> url = new HashMap<String, String>();
				url.put("url", res.getResurl());
				node.setAttributes(url);
				nodes.add(node);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return nodes;
	}

}
